using System.Text.Json;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using UniversalAdmin.Application.Services;
using UniversalAdmin.Infrastructure.Configurations;

namespace UniversalAdmin.Infrastructure.Services;

public class XunfeiEmbeddingService : IEmbeddingService
{
    private readonly HttpClient _httpClient;
    private readonly XunfeiConfig _config;
    private readonly ILogger<XunfeiEmbeddingService> _logger;

    public XunfeiEmbeddingService(
        HttpClient httpClient,
        IOptions<XunfeiConfig> config,
        ILogger<XunfeiEmbeddingService> logger)
    {
        _httpClient = httpClient;
        _config = config.Value;
        _logger = logger;
    }

    public async Task<float[]> GenerateEmbeddingAsync(string text, bool isQuery = false)
    {
        try
        {
            var request = new
            {
                header = new
                {
                    app_id = _config.AppId,
                    status = 3
                },
                parameter = new
                {
                    emb = new
                    {
                        feature = new
                        {
                            encoding = "utf8",
                            text = text
                        }
                    }
                },
                payload = new
                {
                    emb_data = new
                    {
                        text = text
                    }
                }
            };

            var content = JsonSerializer.Serialize(request);
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, $"https://{_config.EmbeddingDomain}{_config.EmbeddingPath}")
            {
                Content = new StringContent(content, System.Text.Encoding.UTF8, "application/json")
            };

            // 添加认证头
            var authHeader = GenerateAuthHeader();
            requestMessage.Headers.Add("Authorization", authHeader);

            var response = await _httpClient.SendAsync(requestMessage);
            response.EnsureSuccessStatusCode();

            var responseContent = await response.Content.ReadAsStringAsync();
            var responseObj = JsonSerializer.Deserialize<JsonElement>(responseContent);

            if (responseObj.TryGetProperty("header", out var headerElement) &&
                headerElement.TryGetProperty("code", out var codeElement) &&
                codeElement.GetInt32() == 0)
            {
                if (responseObj.TryGetProperty("payload", out var payloadElement) &&
                    payloadElement.TryGetProperty("emb", out var embElement) &&
                    embElement.TryGetProperty("feature", out var featureElement) &&
                    featureElement.TryGetProperty("embedding", out var embeddingElement))
                {
                    return ParseEmbedding(embeddingElement);
                }
            }

            _logger.LogError("Failed to generate embedding: {Response}", responseContent);
            throw new Exception("Failed to generate embedding");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error generating embedding for text: {Text}", text);
            throw;
        }
    }

    public async Task<List<float[]>> GenerateEmbeddingsAsync(List<string> texts, bool isQuery = false)
    {
        var embeddings = new List<float[]>();
        
        foreach (var text in texts)
        {
            var embedding = await GenerateEmbeddingAsync(text, isQuery);
            embeddings.Add(embedding);
        }

        return embeddings;
    }

    private string GenerateAuthHeader()
    {
        // 这里需要实现讯飞星火的认证逻辑
        // 通常涉及HMAC-SHA256签名
        var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
        var signatureOrigin = $"host: {_config.EmbeddingDomain}\n" +
                             $"date: {timestamp}\n" +
                             $"GET {_config.EmbeddingPath} HTTP/1.1";
                             
        var signature = ComputeHmacSha256(signatureOrigin, _config.ApiSecret);
        var authorizationOrigin = $"api_key=\"{_config.ApiKey}\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"{signature}\"";
        var authorization = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(authorizationOrigin));
        
        return $"Xunfei authorization={authorization}, date={timestamp}";
    }

    private string ComputeHmacSha256(string data, string key)
    {
        using var hmac = new System.Security.Cryptography.HMACSHA256(System.Text.Encoding.UTF8.GetBytes(key));
        var hash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(data));
        return Convert.ToBase64String(hash);
    }

    private float[] ParseEmbedding(JsonElement embeddingElement)
    {
        if (embeddingElement.ValueKind == JsonValueKind.String)
        {
            // 如果是字符串，可能是Base64编码的
            var base64 = embeddingElement.GetString() ?? string.Empty;
            var bytes = Convert.FromBase64String(base64);
            return ConvertToFloatArray(bytes);
        }
        else if (embeddingElement.ValueKind == JsonValueKind.Array)
        {
            // 如果是数组，直接解析
            return embeddingElement.EnumerateArray().Select(x => x.GetSingle()).ToArray();
        }

        throw new Exception("Unsupported embedding format");
    }

    private float[] ConvertToFloatArray(byte[] bytes)
    {
        var result = new float[bytes.Length / 4];
        for (int i = 0; i < result.Length; i++)
        {
            result[i] = BitConverter.ToSingle(bytes, i * 4);
        }
        return result;
    }
}